package com.metaera.app.ui.popup;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lxj.xpopup.impl.FullScreenPopupView;
import com.metaera.app.MetaEraApplication;
import com.metaera.app.R;
import com.metaera.app.data.model.ArticleListResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.utils.DateUtils;
import com.metaera.app.utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * 快讯分享
 */
public class ShareFlashNewsPopup extends FullScreenPopupView {


    protected ArticleListResponse mArticle;

    public ShareFlashNewsPopup(@NonNull Context context) {
        super(context);
    }

    public ShareFlashNewsPopup(@NonNull Context context, ArticleListResponse article) {
        super(context);
        mArticle = article;
    }


    @Override
    protected int getImplLayoutId() {

        return R.layout.popup_share_flash_news_details;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        TextView tvDate = findViewById(R.id.tv_date);
        TextView tvTitle = findViewById(R.id.tv_title);
        TextView tvContent = findViewById(R.id.tv_content);

        findViewById(R.id.tv_wechat).setOnClickListener(v -> share2WX());
        findViewById(R.id.tv_moments).setOnClickListener(v -> share2Friend());

        findViewById(R.id.tv_download).setOnClickListener(v -> methodRequiresTwoPermission());

        findViewById(R.id.tv_link).setOnClickListener(v -> {
            dismiss();

            ClipboardManager cm = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("Simple text", ApiParam.LINK_SHARE_5 + mArticle.getId()));
            ToastUtils.makeText("复制成功");
        });

        findViewById(R.id.button_cancel).setOnClickListener(v -> dismiss());

        tvTitle.setText(mArticle.getTitle());
        tvContent.setText(mArticle.getContent());
        tvDate.setText(DateUtils.getTime(mArticle.getRelease_time_stamp(), DateUtils.PATTERN_7));
    }


    public final int RC_CAMERA_AND_LOCATION = 1; // requestCode

    @AfterPermissionGranted(RC_CAMERA_AND_LOCATION)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            new Thread(() -> {
                String path = saveImageToGallery(getContext(), saveImage());
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(getContext(), "图片保存至" + path, Toast.LENGTH_SHORT).show());
            }).start();
        } else {

            EasyPermissions.requestPermissions(getActivity(), "申请获取存储权限", RC_CAMERA_AND_LOCATION, perms);
        }
    }

//    private void share2WX() {
//        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
//            ToastUtils.makeText("您还未安装微信客户端");
//
//        } else {
//            Bitmap bitmap = saveImage();
//            String bitmapPath = saveImageToGallery(getContext(), bitmap);
//            WXSharePic(true, bitmap, bitmapPath);
//        }
//
//        dismiss();
//    }
//
//
//    // 分享至朋友圈
//    private void share2Friend() {
//        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
//            ToastUtils.makeText("您还未安装微信客户端");
//
//        } else {
//            Bitmap bitmap = saveImage();
//            String bitmapPath = saveImageToGallery(getContext(), bitmap);
//            WXSharePic(false, bitmap, bitmapPath);
//        }
//
//        dismiss();
//    }
//
//    private void WXSharePic(final boolean isSession, Bitmap bitmap, String path) {
//        // 初始化WXImageObject和WXMediaMessage对象
//        WXImageObject imageObject;
//        if (path != null && path.length() > 0) {
//            imageObject = new WXImageObject();
//            imageObject.setImagePath(path);
//
//        } else {
//            imageObject = new WXImageObject(bitmap);
//        }
//
//        WXMediaMessage wxMediaMessage = new WXMediaMessage();
//        wxMediaMessage.mediaObject = imageObject;
//
//        // 设置缩略图
//        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
//        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//        wxMediaMessage.thumbData = stream.toByteArray(); // 图片
//        bitmap.recycle();
//
//        // 构造一个Req
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = wxMediaMessage;
//        //表示发送给朋友圈 WXSceneTimeline, 表示发送给朋友 WXSceneSession
//        req.scene = isSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
//        // 调用api接口发送数据到微信
//        MetaEraApplication.sWxApi.sendReq(req);
//    }

    private Bitmap saveImage() {
        // 生成bitmap
        View v = findViewById(R.id.layout_container);
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.parseColor("#000988"));
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    // 保存相册到相册
    public String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = context.getResources().getString(R.string.app_name);
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        String imageName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, imageName);
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(currentFile.getPath()))));

        return currentFile.getPath();
    }


    // 分享至微信
    private void share2WX() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            new Thread(() -> share2WX(SendMessageToWX.Req.WXSceneSession)).start();
        }
    }


    // 分享至朋友圈
    private void share2Friend() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            new Thread(() -> share2WX(SendMessageToWX.Req.WXSceneTimeline)).start();
        }

        dismiss();
    }

    // 分享到微信
    private void share2WX(int scene) {
//        try {
            // title, desc, link, image

            WXWebpageObject wxWebpageObject = new WXWebpageObject();
            wxWebpageObject.webpageUrl = ApiParam.LINK_SHARE_5 + mArticle.getId(); // 链接
            WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
            wxMediaMessage.title = mArticle.getTitle(); // 标题
            wxMediaMessage.description = ""; // 描述

            // 图片

//            if (drawableId != 0){
                wxMediaMessage.setThumbImage(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

//            } else if (imageLink != null){
//                Bitmap thumb = BitmapFactory.decodeStream(new URL("mShareModel.imageUrl").openStream());
//                Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, 120, 150, true);
//                ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//                wxMediaMessage.thumbData = stream.toByteArray(); // 图片
//                thumb.recycle();
//            }

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.scene = scene;
            req.message = wxMediaMessage;
            req.transaction = String.valueOf(System.currentTimeMillis());
            MetaEraApplication.sWxApi.sendReq(req);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            dismiss();
//        }
    }

}
